package com.example.lotterysystem.service.activitystatus.operator;

import com.example.lotterysystem.dao.dataobject.ActivityPrizeDO;
import com.example.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.example.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.example.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class PrizeOperator extends AbstractActivityOperator {
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        Long activityId = convertActivityStatusDTO.getActivityId();
        Long prizeId = convertActivityStatusDTO.getPrizeId();
        ActivityPrizeStatusEnum targetPrizeStatus = convertActivityStatusDTO.getTargetPrizeStatus();
        // 活动 id、奖品 id 和 奖品目标状态是否为空
        if (null == activityId
                || null == prizeId
                || null == targetPrizeStatus) {
            log.warn("needConvert 中 activityId 或 targetPrizeStatus 为空");
            return false;
        }
        // 活动奖品是否存在
        ActivityPrizeDO activityPrizeDO = activityPrizeMapper.selectByAPId(activityId, prizeId);
        if (null == activityPrizeDO) {
            log.warn("needConvert 中 {} 活动 奖品 {} 不存在", activityId, prizeId);
            return false;
        }
        // 奖品目标状态是否需要转化
        if (targetPrizeStatus.name().equalsIgnoreCase(activityPrizeDO.getStatus())) {
            return false;
        }

        // 校验完成，需要进行状态转换
        return true;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            log.info("活动 {} 奖品 {} 状态转化", convertActivityStatusDTO.getActivityId(), convertActivityStatusDTO.getPrizeId());
            return activityPrizeMapper.updateStatus(convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getPrizeId(),
                    convertActivityStatusDTO.getTargetPrizeStatus()) > 0;
        } catch (Exception e) {
            log.warn("convert {} 活动奖品 {} 状态转化失败",
                    convertActivityStatusDTO.getActivityId(),
                    convertActivityStatusDTO.getPrizeId(), e);
            return false;
        }
    }
}
